using System;
using System.Linq;
using System.Reflection;

using TrueCode.DependencyManager.BuildActions.Instantiating;

namespace TrueCode.DependencyManager.Services.Instantiating
{
  public class ParameterlessCtorProvider : IConstructorProvider
  {
    #region Implementation of IConstructorProvider
    public ConstructorInfo GetConstructor( Type type )
    {
      var constructors = type.GetConstructors();

      #region Assert that constructors is not empty is type is class (not struct)
      if( constructors.Length == 0 && !type.IsValueType )
      {
        var exc = new ArgumentException( "This type does not contain any constructors", "type" );
        exc.Data.Add( "Type", type );
        throw exc;
      }
      #endregion

      var ctor = constructors.FirstOrDefault( c => c.GetParameters().Length == 0 );
      if( ctor == null )
        throw new ArgumentException( "Type " + type.FullName + " does not contain parameterless constructor" );
      return ctor;
    }
    #endregion
  }
}